// 剪贴板管理器
export class ClipboardManager {
    constructor() {
        this.pasteCallbacks = new Map();
        this.activePasteArea = null;
    }

    // 初始化剪贴板监听
    init() {
        document.addEventListener('paste', this.handlePaste.bind(this));

        // 监听全局点击事件，确定用户意图
        document.addEventListener('click', this.handleGlobalClick.bind(this));
        document.addEventListener('focusin', this.handleFocusIn.bind(this));
    }

    // 处理全局点击事件
    handleGlobalClick(event) {
        // 检查点击是否在粘贴区域内
        for (const [elementId] of this.pasteCallbacks) {
            const element = document.getElementById(elementId);
            if (element && element.contains(event.target)) {
                this.setActivePasteArea(elementId);
                break;
            }
        }
    }

    // 处理焦点进入事件
    handleFocusIn(event) {
        for (const [elementId] of this.pasteCallbacks) {
            const element = document.getElementById(elementId);
            if (element && element.contains(event.target)) {
                this.setActivePasteArea(elementId);
                break;
            }
        }
    }

    // 设置活动粘贴区域
    setActivePasteArea(areaId) {
        this.activePasteArea = areaId;

        // 可视化反馈：给活动区域添加高亮
        for (const [elementId] of this.pasteCallbacks) {
            const element = document.getElementById(elementId);
            if (element) {
                if (elementId === areaId) {
                    element.style.borderColor = '#4285f4';
                    element.style.background = '#f0f7ff';
                } else {
                    element.style.borderColor = '#ccc';
                    element.style.background = 'white';
                }
            }
        }

        console.log('活动粘贴区域:', areaId);
    }

    // 注册粘贴回调
    registerPasteArea(elementId, callback) {
        this.pasteCallbacks.set(elementId, callback);

        // 为粘贴区域添加tabindex使其可聚焦
        const element = document.getElementById(elementId);
        if (element) {
            element.setAttribute('tabindex', '0');
            element.style.outline = 'none'; // 移除默认焦点轮廓

            // 添加点击事件监听
            element.addEventListener('click', () => {
                this.setActivePasteArea(elementId);
            });
        }
    }

    // 处理粘贴事件
    async handlePaste(event) {
        const clipboardItems = event.clipboardData?.items;
        if (!clipboardItems) return;

        // 查找图片数据
        for (const item of clipboardItems) {
            if (item.type.indexOf('image') !== -1) {
                const blob = item.getAsFile();
                if (blob) {
                    event.preventDefault();

                    // 使用活动粘贴区域
                    if (this.activePasteArea && this.pasteCallbacks.has(this.activePasteArea)) {
                        const callback = this.pasteCallbacks.get(this.activePasteArea);
                        await callback(blob);
                    } else {
                        // 如果没有明确的活动区域，尝试智能判断
                        await this.handleSmartPaste(blob, event);
                    }
                    break;
                }
            }
        }
    }

    // 智能粘贴处理：根据上下文判断用户意图
    async handleSmartPaste(blob, event) {
        // 检查哪个粘贴区域是可见且更可能的目标
        let targetArea = null;

        // 优先考虑搜索区域（因为搜索可能更频繁）
        const searchArea = document.getElementById('searchPasteArea');
        const libraryArea = document.getElementById('libraryPasteArea');

        if (searchArea && searchArea.offsetParent !== null) {
            targetArea = 'searchPasteArea';
        } else if (libraryArea && libraryArea.offsetParent !== null) {
            targetArea = 'libraryPasteArea';
        }

        if (targetArea && this.pasteCallbacks.has(targetArea)) {
            console.log('智能选择粘贴区域:', targetArea);
            const callback = this.pasteCallbacks.get(targetArea);
            await callback(blob);
        } else {
            console.warn('无法确定粘贴目标');
        }
    }

    // 生成默认文件名
    generateDefaultFilename() {
        const now = new Date();
        const timestamp = now.toISOString().replace(/[:.]/g, '-').split('.')[0];
        return `screenshot-${timestamp}.png`;
    }
}